﻿/* dk2Repository - Copyright (C) 2011 Daniel Kuczewski http://www.dk2.de/

 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */

using System.Collections.Generic;
using dk2Database.Commands;
using dk2Repository.Commands;
using dk2Repository.Interfaces;
using dk2Repository.QueryBuilder;

namespace dk2Repository
{
    internal sealed class CommandFactory<T> where T : class, new()
    {
        private readonly ISqlBuilder _sqlBuilder;
        private readonly IMapping _mapping;

        public CommandFactory(ISqlBuilder sqlBuilder, IMapping mapping)
        {
            _mapping = mapping;
            _sqlBuilder = sqlBuilder;
        }

        private string _createTable;
        private string _createTableIfNotExists;
        public ExecuteCommand CreateCreateTable(bool ifnotexist)
        {
            if(string.IsNullOrEmpty(_createTable))
            {
                var builder = _sqlBuilder.CreateCreateTableBuilder();
                builder.SetTable(_mapping.Table);

                foreach (var column in _mapping.Columns)
                {
                    builder.AddColumn(column.ColumnName, column.DbType, column.IsNullable, column.Length, column.IsPk, column.IsAutoInc);
                }

                builder.CreateIfNotExists = true;
                _createTableIfNotExists = builder.CreateSql();

                builder.CreateIfNotExists = false;
                _createTable = builder.CreateSql();
            }

            return ifnotexist ? new ExecuteCommand(_createTableIfNotExists) : new ExecuteCommand(_createTable);
        }


        public QueryEntityCommandBase<IList<T>> CreateFindAll()
        {
            var builder = _sqlBuilder.CreateSelectBuilder();

            builder.SetTable(_mapping.Table);

            foreach (var mapping in _mapping.Columns)
            {
                builder.AddColumn(mapping.ColumnName);
            }

            return new MappedQueryCommand<T>(builder.CreateSql());
        }

        public QueryEntityCommandBase<IList<T>> CreateFindAll(string where, string order, bool references, params object[] parameters)
        {
            var builder = _sqlBuilder.CreateSelectBuilder();

            builder.SetTable(_mapping.Table);

            foreach (var mapping in _mapping.Columns)
            {
                builder.AddColumn(_mapping.Table + "." + mapping.ColumnName);
            }

            if(!string.IsNullOrEmpty(where))
                builder.Where.Add(where);

            if(!string.IsNullOrEmpty(order))
                builder.AddOrder(order);

            if (references)
            {
                foreach (var reference in _mapping.References)
                {
                    builder.AddJoin( EnumJoinMode.LeftOuter, _mapping.Table, reference.ReferenceMapping.Table, reference.ForeignKeyColumn, reference.CanidateKeyColumn);
                    foreach (var mapping in reference.ReferenceMapping.Columns)
                    {
                        builder.AddColumn(reference.ReferenceMapping.Table + "." + mapping.ColumnName, reference.Prefix + mapping.ColumnName);
                    }
                }

            }

            return new MappedQueryCommand<T>(builder.CreateSql(), parameters);
        }


        public QueryEntityCommandBase<IList<T>> CreateFindById(object id, bool references)
        {
            var builder = _sqlBuilder.CreateSelectBuilder();

            builder.SetTable(_mapping.Table);

            foreach (var mapping in _mapping.Columns)
            {
                builder.AddColumn(mapping.ColumnName);
            }

            builder.Where.Add(_mapping.Columns.PrimaryKeys[0].ColumnName, EnumCompareMode.Equals);

            if (references)
            {
                foreach (var reference in _mapping.References)
                {
                    builder.AddJoin(EnumJoinMode.LeftOuter, _mapping.Table, reference.ReferenceMapping.Table, reference.ForeignKeyColumn, reference.CanidateKeyColumn);
                    foreach (var mapping in reference.ReferenceMapping.Columns)
                    {
                        builder.AddColumn(reference.ReferenceMapping.Table + "." + mapping.ColumnName, reference.Prefix + mapping.ColumnName);
                    }
                }

            }

            var cmd = new MappedQueryCommand<T>(builder.CreateSql());
            cmd.Parameters.Add(id);

            return cmd;
        }


        private string _insertSql;
        private CommandBase.CommandParameters _insertParameters;
        public ExecuteCommand CreateInsert(T item)
        {
            if (_insertSql == null)
            {
                _insertParameters = new CommandBase.CommandParameters();

                var builder = _sqlBuilder.CreateInsertBuilder();

                builder.SetTable(_mapping.Table);
                foreach (var columnMapping in _mapping.Columns)
                {
                    if (columnMapping.IsAutoInc) 
                        continue;
                    
                    builder.AddValue(columnMapping.ColumnName);
                    _insertParameters.Add(columnMapping);
                }

                builder.AutoInc = (_mapping.PkType == EnumPkType.SingleAutoinc);

                _insertSql = builder.CreateSql();

            }

            return new MappedInsertCommand<T>(item, _mapping.Columns.PrimaryKeys[0], _mapping.PkType, _insertSql, _insertParameters);
        }

        private string _updateSql;
        private CommandBase.CommandParameters _updateParameters;
        public ExecuteCommand CreateUpdate(T item)
        {
            if (_updateSql == null)
            {
                _updateParameters = new CommandBase.CommandParameters();

                var builder = _sqlBuilder.CreateUpdateBuilder();

                builder.SetTable(_mapping.Table);
                foreach (var columnMapping in _mapping.Columns.WithoutPrimaryKey)
                {
                    builder.AddValue(columnMapping.ColumnName);
                    _updateParameters.Add(columnMapping);
                }

                foreach (var columnMapping in _mapping.Columns.PrimaryKeys)
                {
                    builder.Where.Add(columnMapping.ColumnName, EnumCompareMode.Equals);
                    _updateParameters.Add(columnMapping);
                }

                _updateSql = builder.CreateSql();
            }

            return new MappedExecuteCommand<T>(item, _updateSql, _updateParameters);
        }

        private string _deleteSql;
        private CommandBase.CommandParameters _deleteParameters;
        public ExecuteCommand CreateDelete(T item)
        {
            if (_deleteSql == null)
            {
                _deleteParameters = new CommandBase.CommandParameters();

                var builder = _sqlBuilder.CreateDeleteBuilder();

                builder.SetTable(_mapping.Table);

                foreach (var columnMapping in _mapping.Columns.PrimaryKeys)
                {
                    builder.Where.Add(columnMapping.ColumnName, EnumCompareMode.Equals);
                    _deleteParameters.Add(columnMapping);
                }

                _deleteSql = builder.CreateSql();
            }

            return new MappedExecuteCommand<T>(item, _deleteSql, _deleteParameters);
        }
    }
}
